package com.yboot.starter.tenant.core.mybatis;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.yboot.starter.common.core.security.SecurityUserVO;
import com.yboot.starter.common.core.security.UserContext;
import com.yboot.starter.tenant.config.TenantProperties;
import com.yboot.starter.tenant.core.context.TenantContextHolder;
import lombok.RequiredArgsConstructor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@RequiredArgsConstructor
public class MybatisTenantHandler implements TenantLineHandler {
    private final TenantProperties tenantProperties;
    private final UserContext userContext;


    public String getTenantIdColumn() {
        return StringUtils.hasLength(this.tenantProperties.getTenantIdColumn()) ? this.tenantProperties.getTenantIdColumn() : "tenant_id";
    }

    public Expression getTenantId() {
        String tenantId = TenantContextHolder.getTenantId();
        if (StringUtils.hasLength(tenantId)) {
            return new StringValue(tenantId);
        } else {
            SecurityUserVO user = userContext.getUser().orElseGet(SecurityUserVO::new);
            if (StringUtils.hasLength(user.getTenantId())) {
                return new StringValue(user.getTenantId());
            } else {
                throw new RuntimeException("未获取到租户信息");
            }
        }
    }

    public boolean ignoreTable(String tableName) {
        if (TenantContextHolder.isIgnore()) {
            return true;
        } else {
            List<String> ignoreTableNames = this.tenantProperties.getIgnoreTableNames();
            return !CollectionUtils.isEmpty(ignoreTableNames) && ignoreTableNames.contains(tableName);
        }
    }

//    private AuthenticatedUser getAuthenticatedUser() {
//        return AuthenticationContextHolder.getRequiredAuthenticatedUser();
//    }
}
